﻿using System;
using System.Collections;
using System.Text;
using System.Management;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Microsoft.Win32;
namespace IPProvider.Service
{
    /**/
    /// <summary>
    /// IPProvider 的摘要说明。
    /// </summary>
    public class IPProviders
    {

        public IPProviders()
        {

        }
        /// <summary>
        /// 设置DNS
        /// </summary>
        /// <param name="dns"></param>
        public static void SetDNS(string[] dns,string IPName)
        {
            SetIPAddress(null, null, null, dns,IPName);
        }
        /**/
        /// <summary>
        /// 设置网关
        /// </summary>
        /// <param name="getway"></param>
        public static void SetGetWay(string getway,string IPName)
        {
            SetIPAddress(null, null, getway, null, null);
        }
        
        /**/
        /// <summary>
        /// 设置IP地址和掩码
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        public static void SetIPAddress(string ip, string submask, string IPName)
        {
            SetIPAddress(ip, submask, null, null, IPName);
        }
        /**/
        /// <summary>
        /// 设置IP地址，掩码和网关
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        /// <param name="getway"></param>
        public static void SetIPAddress(string ip, string submask, string getway,string IPName)
        {
            SetIPAddress(ip,submask,getway,null,IPName);
        }
        /**/
        /// <summary>
        /// 设置IP地址，掩码，网关和DNS
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="submask"></param>
        /// <param name="getway"></param>
        /// <param name="dns"></param>
        /// <param name="IPName"></param>
        public static void SetIPAddress(string ip, string submask, string getway, string[] dns,string IPName)
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            foreach (ManagementObject mo in moc)
            {
                //如果没有启用IP设置的网络设备则跳过
                if (!(bool)mo["IPEnabled"]) continue;
                string ipName= mo["Caption"].ToString();
                if (IPName != ipName) continue;
                //设置IP地址和掩码
                if (ip != null && submask != null)
                {
                    inPar = mo.GetMethodParameters("EnableStatic");
                    inPar["IPAddress"] = new string[] { ip};
                    
                    inPar["SubnetMask"] =new string[]{ submask};
                    outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                }
                //设置网关地址
                if (getway != null)
                {
                    inPar = mo.GetMethodParameters("SetGateways");
                    inPar["DefaultIPGateway"] =new string[]{ getway};
                    outPar = mo.InvokeMethod("SetGateways", inPar, null);
                }

                //设置DNS地址
                if (dns != null)
                {
                    inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                    inPar["DNSServerSearchOrder"] = dns;
                    outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                }
                break;
            }
        }

        /**/
        /// <summary>
        /// 启用DHCP服务器
        /// </summary>
        public static void EnableDHCP()
        {
            ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = wmi.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                //如果没有启用IP设置的网络设备则跳过
                if (!(bool)mo["IPEnabled"]) continue;

                //重置DNS为空
                mo.InvokeMethod("SetDNSServerSearchOrder", null);
                //开启DHCP
                mo.InvokeMethod("EnableDHCP", null);
            }
        }
        /// <summary>
        /// 获取 IP 信息 集合
        /// </summary>
        /// <returns></returns>
        public static IDictionary<string, IPInfo> GetIPInfo()
        {
            IDictionary<string, IPInfo> dicIPInfo = new Dictionary<string, IPInfo>();
            RegistryKey rk = null;//RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,RegistryView.Default);
            
            try
            {
                int id = 0;
                ManagementClass class2 = new ManagementClass("Win32_NetworkAdapterConfiguration");
                foreach (ManagementObject obj2 in class2.GetInstances())
                {
                    if (!((bool)obj2["IPEnabled"]))
                    {
                        continue;
                    }
                    IPInfo item = new IPInfo();
                    item.Id = id;
                    item.IPName = obj2["Caption"].ToString();
                    item.Mac = obj2["MacAddress"].ToString();
                    string[] strArray = (string[])obj2["IPAddress"];
                    item.IPAddress = (strArray == null) ? "0.0.0.0" : strArray[0];
                    if (strArray[0] != "0.0.0.0")
                    {
                        //HKEY_LOCAL_MACHINE\
                        string url = @"SYSTEM\ControlSet001\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\" + obj2["SettingID"] + @"\Connection\";
                        rk = Registry.LocalMachine.OpenSubKey(url);
                        if (rk!=null)
                        {
                            object objName = rk.GetValue("Name");
                            item.ConnectionName = objName != null ? objName.ToString() : "";
                        }
                        string[] strArray2 = (string[])obj2["IPSubnet"];
                         
                        item.Submask = (strArray2 == null) ? "0.0.0.0" : strArray2[0];
                        string[] strArray3 = (string[])obj2["DefaultIPGateway"];
                        item.GetWay = (strArray3 == null) ? "0.0.0.0" : strArray3[0];
                        string[] strArray4 = (string[])obj2["DNSServerSearchOrder"];
                        item.DNS = (strArray4 == null) ? "0.0.0.0" : strArray4[0];
                        if ((strArray4 != null) && (strArray4.Length > 1))
                        {
                            item.DNSBak = strArray4[1];
                        }

                        item.Mac = obj2["MacAddress"].ToString();
                    }

                    dicIPInfo.Add(item.Id.ToString(), item);
                    id++;
                }
            }
            catch (Exception exception)
            {
                throw new Exception("IP获取失败!" + exception.Message);
            }
            return dicIPInfo;
        }

        /**/
        /// <summary>
        /// 判断是否IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIPAddress(string ip)
        {
            string[] arr = ip.Split('.');
            if (arr.Length != 4) return false;

            string pattern = @"\d{1,3}";
            for (int i = 0; i < arr.Length; i++)
            {
                string d = arr[i];
                if (i == 0 && d == "0") return false;
                if (!Regex.IsMatch(d, pattern)) return false;
                if (d != "0")
                {
                    d = d.TrimStart('0');
                    if (d == "") return false;

                    if (int.Parse(d) > 255) return false;
                }
            }
            return true;
        }
    }
}
